<?php

App::uses('AppController', 'Controller');

class LeaveTypesController extends AppController {
	
	public $uses = array('LeaveType', 'Rule');
	
	public function index() {
		$leaveTypes = $this->LeaveType->find('all');
		
		$this->set(compact('leaveTypes'));
	}
	
	private function _setCommonData() {
	    $rules = $this->Rule->all();
	    $this->set(compact('rules'));
	}
	
	/**
	 * CREATE
	 */
	public function create() {
	    $this->_setCommonData();
		$this->set('data', $this->LeaveType->create());
		$this->render('form');
	}
	
	/**
	 * READ
	 */
	public function show($id) {
		$this->set('data', $this->LeaveType->findById($id));
	}
	
	/**
	 * EDIT (UPDATE)
	 */
	public function edit($id) {
	    $this->_setCommonData();
		$this->set('data', $this->LeaveType->findById($id));
		$this->render('form');
	}
	
	/**
	 * SAVE (UPDATE)
	 */
	public function save() {
		if ($this->request->is('post')) {
			$data = $this->data;
			$data = $this->LeaveType->refactor($data);
			$this->LeaveType->create($data);
			
			if (! $this->LeaveType->validates()) {
			    $this->_setCommonData();
				$this->set('data', $data);
				$this->setFlash('Invalid data!');
				return $this->render('form');
			}
			
			if (! $this->LeaveType->saveAll($data)) {
			    $this->_setCommonData();
				$this->set('data', $data);
				$this->setFlash('Error saving data.');
				return $this->render('form');
			}
			
			$this->setFlash('Saved.', 'ok');
			$this->redirect('edit/' . $this->LeaveType->id);
		}
		
		$this->redirect('index');
	}
	
	/**
	 * DELETE
	 */
	public function delete($id) {
		if (! $this->LeaveType->delete($id)) {
			$this->setFlash('Error deleting LeaveType!');
		} else {
			$this->setFlash('LeaveType deleted', 'ok');
		}
		
		$this->redirect('index');
	}
}
